<?php
require_once 'common/config.php';
require_once 'common/functions.php';

// 检查登录状态
check_login();

$db = db_connect();

// 获取帖子ID
$id = isset($_GET['id']) ? intval($_GET['id']) : 0;
if (!$id) {
    redirect('posts.php', '无效的帖子ID', 'error');
}

// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $title = trim($_POST['title']);
    $content = trim($_POST['content']);
    $status = isset($_POST['status']) ? 1 : 0;
    $remove_image = isset($_POST['remove_image']) ? true : false;
    
    // 验证输入
    if (empty($title)) {
        $error = '标题不能为空';
    } elseif (empty($content)) {
        $error = '内容不能为空';
    } else {
        try {
            $db->beginTransaction();
            
            $image_path = null;
            
            // 处理图片上传
            if (isset($_FILES['image']) && $_FILES['image']['error'] == 0) {
                $allowed_types = ['jpg', 'jpeg', 'png', 'gif'];
                $upload_dir = '../api/user/uploads/posts/';
                $filename_prefix = date('Ymd_His') . '_' . uniqid() . '.';
                
                $result = handle_file_upload($_FILES['image'], $allowed_types, $upload_dir, $filename_prefix);
                if ($result['success']) {
                    $image_path = 'uploads/posts/' . $result['filename'];
                    
                    // 如果有旧图片，删除它
                    $stmt = $db->prepare("SELECT image FROM posts WHERE id = ?");
                    $stmt->execute([$id]);
                    $old_image = $stmt->fetchColumn();
                    if ($old_image) {
                        $old_path = '../api/user/' . $old_image;
                        if (file_exists($old_path)) {
                            unlink($old_path);
                        }
                    }
                } else {
                    throw new Exception($result['message']);
                }
            }
            
            // 如果选择移除图片
            if ($remove_image) {
                $stmt = $db->prepare("SELECT image FROM posts WHERE id = ?");
                $stmt->execute([$id]);
                $old_image = $stmt->fetchColumn();
                if ($old_image) {
                    $old_path = '../api/user/' . $old_image;
                    if (file_exists($old_path)) {
                        unlink($old_path);
                    }
                }
                $image_path = '';
            }
            
            // 更新帖子
            $sql = "UPDATE posts SET title = ?, content = ?, status = ?, updated_at = NOW()";
            $params = [$title, $content, $status];
            
            if ($image_path !== null) {
                $sql .= ", image = ?";
                $params[] = $image_path;
            }
            
            $sql .= " WHERE id = ?";
            $params[] = $id;
            
            $stmt = $db->prepare($sql);
            $stmt->execute($params);
            
            $db->commit();
            redirect('posts.php', '帖子更新成功');
        } catch (Exception $e) {
            $db->rollBack();
            $error = '更新失败：' . $e->getMessage();
        }
    }
}

// 获取帖子信息
$stmt = $db->prepare("SELECT * FROM posts WHERE id = ?");
$stmt->execute([$id]);
$post = $stmt->fetch();

if (!$post) {
    redirect('posts.php', '帖子不存在', 'error');
}
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>编辑帖子 - <?php echo SITE_NAME; ?></title>
    <link rel="stylesheet" href="assets/css/style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <style>
    .image-preview {
        margin: 15px 0;
        text-align: center;
    }
    .image-preview img {
        max-width: 300px;
        max-height: 200px;
        border-radius: 4px;
        box-shadow: 0 2px 5px rgba(0,0,0,0.1);
    }
    .image-actions {
        margin-top: 10px;
    }
    .checkbox-group {
        margin-top: 10px;
        color: #666;
    }
    </style>
</head>
<body>
    <div class="wrapper">
        <?php include 'includes/sidebar.php'; ?>
        
        <div class="main-content">
            <div class="content">
                <h2>编辑帖子</h2>
                
                <?php if (isset($error)): ?>
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-circle"></i>
                    <?php echo $error; ?>
                </div>
                <?php endif; ?>
                
                <div class="form-container">
                    <form method="post" enctype="multipart/form-data">
                        <div class="form-group">
                            <label for="title">标题 <span class="required">*</span></label>
                            <input type="text" id="title" name="title" value="<?php echo htmlspecialchars($post['title']); ?>" required>
                        </div>
                        
                        <div class="form-group">
                            <label for="content">内容 <span class="required">*</span></label>
                            <textarea id="content" name="content" rows="10" required><?php echo htmlspecialchars($post['content']); ?></textarea>
                        </div>
                        
                        <div class="form-group">
                            <label>帖子图片</label>
                            <?php if ($post['image']): ?>
                            <div class="image-preview">
                                <img src="<?php echo '../api/user/' . $post['image']; ?>" alt="当前图片">
                                <div class="checkbox-group">
                                    <label>
                                        <input type="checkbox" name="remove_image" value="1">
                                        删除当前图片
                                    </label>
                                </div>
                            </div>
                            <?php endif; ?>
                            <div class="image-actions">
                                <input type="file" name="image" accept="image/*">
                                <div class="help-text">支持 jpg, jpeg, png, gif 格式，建议尺寸不超过 1920×1080</div>
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label class="checkbox-label">
                                <input type="checkbox" name="status" value="1" <?php echo $post['status'] ? 'checked' : ''; ?>>
                                启用帖子
                            </label>
                        </div>
                        
                        <div class="form-group">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-save"></i> 保存修改
                            </button>
                            <a href="posts.php" class="btn btn-secondary">
                                <i class="fas fa-arrow-left"></i> 返回列表
                            </a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <script>
    // 预览选择的图片
    document.querySelector('input[type="file"]').addEventListener('change', function(e) {
        const file = e.target.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = function(e) {
                let preview = document.querySelector('.image-preview');
                if (!preview) {
                    preview = document.createElement('div');
                    preview.className = 'image-preview';
                    document.querySelector('.image-actions').before(preview);
                }
                preview.innerHTML = `<img src="${e.target.result}" alt="预览图片">`;
            }
            reader.readAsDataURL(file);
        }
    });

    // 当选择删除图片时，清空文件选择
    document.querySelector('input[name="remove_image"]')?.addEventListener('change', function(e) {
        if (e.target.checked) {
            document.querySelector('input[type="file"]').value = '';
            const preview = document.querySelector('.image-preview img');
            if (preview) {
                preview.style.opacity = '0.3';
            }
        } else {
            const preview = document.querySelector('.image-preview img');
            if (preview) {
                preview.style.opacity = '1';
            }
        }
    });
    </script>
</body>
</html> 